import java.awt.Cursor;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle;
import javax.swing.SwingWorker;
import javax.swing.border.BevelBorder;

/*
 * ApplicationView.java
 *
 * Created on Jun 29, 2010, 11:38:40 PM
 */

/**
 *
 * @author Sean
 */
@SuppressWarnings("serial")
public class ApplicationView extends javax.swing.JFrame {
	private Timetable tbl;
	private Calendar cal;
	/** Creates new form ApplicationView */
	public ApplicationView() {
		cal = new Calendar();
		initComponents();
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	private void initComponents() {

		fileChooser = new javax.swing.JFileChooser();
		calendarPanel = new javax.swing.JPanel();
		calendarPanelHeaderLabel = new javax.swing.JLabel();
		usernameField = new javax.swing.JTextField();
		passwordField = new javax.swing.JPasswordField();
		usernameLabel = new javax.swing.JLabel();
		passwordLabel = new javax.swing.JLabel();
		loginButton = new javax.swing.JButton();
		loginStatusLabel = new javax.swing.JLabel();
		timetablePanel = new javax.swing.JPanel();
		pathField = new javax.swing.JTextField();
		browseButton = new javax.swing.JButton();
		timetablePanelHeaderLabel = new javax.swing.JLabel();
		createCalButton = new javax.swing.JButton();
		menuBar = new javax.swing.JMenuBar();
		fileMenu = new javax.swing.JMenu();
		openTimetableMenuItem = new javax.swing.JMenuItem();
		createCalMenuItem = new javax.swing.JMenuItem();
		helpMenu = new javax.swing.JMenu();
		aboutMenuItem = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Algonquin Timetable Parser");

		calendarPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Google Calendar"));

		calendarPanelHeaderLabel.setText("Please logon to Google...");

		passwordField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				passwordFieldActionPerformed(evt);
			}
		});

		usernameLabel.setText("Username:");

		passwordLabel.setText("Password:");

		loginButton.setText("Login");
		loginButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				loginButtonActionPerformed(evt);
			}
		});

		loginStatusLabel.setForeground(new java.awt.Color(204, 0, 0));
		loginStatusLabel.setText("Not Logged In");

		javax.swing.GroupLayout calendarPanelLayout = new javax.swing.GroupLayout(calendarPanel);
		calendarPanel.setLayout(calendarPanelLayout);
		calendarPanelLayout.setHorizontalGroup(
				calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(calendarPanelLayout.createSequentialGroup()
						.addGap(10, 10, 10)
						.addComponent(calendarPanelHeaderLabel)
						.addContainerGap(115, Short.MAX_VALUE))
						.addGroup(calendarPanelLayout.createSequentialGroup()
								.addContainerGap()
								.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, calendarPanelLayout.createSequentialGroup()
												.addGap(10, 10, 10)
												.addComponent(loginStatusLabel)
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
												.addComponent(loginButton)
												.addGap(10, 10, 10))
												.addGroup(calendarPanelLayout.createSequentialGroup()
														.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
																.addComponent(usernameLabel)
																.addComponent(passwordLabel))
																.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
																		.addComponent(usernameField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
																		.addComponent(passwordField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
																		.addContainerGap())))
		);
		calendarPanelLayout.setVerticalGroup(
				calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(calendarPanelLayout.createSequentialGroup()
						.addComponent(calendarPanelHeaderLabel)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(usernameLabel)
								.addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(passwordLabel)
										.addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(loginButton)
												.addComponent(loginStatusLabel)))
		);

		timetablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Timetable"));
		timetablePanel.setName(""); // NOI18N

		browseButton.setText("Browse");
		browseButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				browseButtonActionPerformed(evt);
			}
		});

		timetablePanelHeaderLabel.setText("Select a timetable...");

		javax.swing.GroupLayout timetablePanelLayout = new javax.swing.GroupLayout(timetablePanel);
		timetablePanel.setLayout(timetablePanelLayout);
		timetablePanelLayout.setHorizontalGroup(
				timetablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(timetablePanelLayout.createSequentialGroup()
						.addContainerGap()
						.addGroup(timetablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timetablePanelLayout.createSequentialGroup()
										.addComponent(pathField, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(browseButton))
										.addComponent(timetablePanelHeaderLabel))
										.addContainerGap())
		);
		timetablePanelLayout.setVerticalGroup(
				timetablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timetablePanelLayout.createSequentialGroup()
						.addComponent(timetablePanelHeaderLabel)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(timetablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(pathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(browseButton))
								.addGap(40, 40, 40))
		);

		createCalButton.setText("Create Calendar!");
		createCalButton.setToolTipText("Create a Google Calendar from your timetable.");
		{
			statusIndicator = new JLabel();
			statusIndicator.setText("Ready.");
			statusIndicator.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
		}
		createCalButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				createCalButtonActionPerformed(evt);
			}
		});

		fileMenu.setText("File");

		openTimetableMenuItem.setText("Open Timetable");
		openTimetableMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				openTimetableMenuItemActionPerformed(evt);
			}
		});
		fileMenu.add(openTimetableMenuItem);

		createCalMenuItem.setText("Create Calendar");
		createCalMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				createCalMenuItemActionPerformed(evt);
			}
		});
		fileMenu.add(createCalMenuItem);

		menuBar.add(fileMenu);

		helpMenu.setText("Help");

		aboutMenuItem.setText("About ATP...");
		aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				aboutMenuItemActionPerformed(evt);
			}
		});
		helpMenu.add(aboutMenuItem);

		menuBar.add(helpMenu);

		setJMenuBar(menuBar);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);

		calendarPanel.getAccessibleContext().setAccessibleName(null);
		timetablePanel.getAccessibleContext().setAccessibleDescription("Timetable");
		layout.setVerticalGroup(layout.createSequentialGroup()
			.addContainerGap()
			.addComponent(calendarPanel, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			.addComponent(timetablePanel, GroupLayout.PREFERRED_SIZE, 78, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 0, Short.MAX_VALUE)
			.addComponent(createCalButton, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			.addComponent(statusIndicator, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE));
		layout.setHorizontalGroup(layout.createParallelGroup()
			.addComponent(statusIndicator, GroupLayout.Alignment.LEADING, 0, 309, Short.MAX_VALUE)
			.addGroup(layout.createSequentialGroup()
			    .addPreferredGap(statusIndicator, calendarPanel, LayoutStyle.ComponentPlacement.INDENT)
			    .addGroup(layout.createParallelGroup()
			        .addComponent(calendarPanel, GroupLayout.Alignment.LEADING, 0, 285, Short.MAX_VALUE)
			        .addComponent(timetablePanel, GroupLayout.Alignment.LEADING, 0, 285, Short.MAX_VALUE)
			        .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			            .addGap(89)
			            .addComponent(createCalButton, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			            .addGap(0, 99, Short.MAX_VALUE)))
			    .addContainerGap()));

		pack();
		this.setSize(317, 326);
	}// </editor-fold>                        

	private void openTimetableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openTimetableMenuItemActionPerformed
		browseForTimetable();
	}//GEN-LAST:event_openTimetableMenuItemActionPerformed

	private void createCalMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createCalMenuItemActionPerformed
		(new CreateCalendar()).execute();
	}//GEN-LAST:event_createCalMenuItemActionPerformed

	/**
	 * Perform action when the login button is pressed
	 * @param evt
	 */
	@SuppressWarnings("deprecation")
	private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
		//Change to wait cursor
		Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
		setCursor(waitCursor);

		//GoogleService will only accept String for password
		if (cal.login(usernameField.getText(), passwordField.getText())){
			loginStatusLabel.setText("Logged In Successfully!");
			loginButton.setEnabled(false);
		}
		else if (cal.getLoginStatus() == -1){
			loginStatusLabel.setText("An Error Occured!");
		}
		//Change back to normal cursor
		Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
		setCursor(normalCursor);
	}//GEN-LAST:event_loginButtonActionPerformed

	private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
		browseForTimetable();
	}//GEN-LAST:event_browseButtonActionPerformed

	private void createCalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createCalButtonActionPerformed
            (new CreateCalendar()).execute();
            //createCalendar();
	}//GEN-LAST:event_createCalButtonActionPerformed

	private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
		loginButtonActionPerformed(evt);
	}//GEN-LAST:event_passwordFieldActionPerformed

	private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
		new AboutView().setVisible(true);
	}//GEN-LAST:event_aboutMenuItemActionPerformed

	/**
	 * Calls appropriate methods to parse timetable and create full calendar
	 */
        private class CreateCalendar extends SwingWorker<Void, String>{
            @Override
            public Void doInBackground(){
		if (cal.getLoginStatus() != 1){     //Not Logged in
			//JOptionPane.showMessageDialog(this, "You must log in first.", "I'm afraid I can't do that...", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		
		tbl = new Timetable(fileChooser.getSelectedFile());
		
		if (Timetable.getFileStatus() == -1){     //No File Open
			//JOptionPane.showMessageDialog(this, "There was an error with the timetable file.", "Bad timetable", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		else if (Timetable.getFileStatus() == -2){     //No File Open
			//JOptionPane.showMessageDialog(this, "Could not find timetable file specified", "Bad timetable", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		else if (Timetable.getFileStatus() != 1){     //No File Open
			//JOptionPane.showMessageDialog(this, "You Must Select a Timetable First!", "I'm afraid I can't do that...", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		//Change to wait cursor
		Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
		setCursor(waitCursor);

		System.out.println(Timetable.getStudentID());
		long start = System.currentTimeMillis();
		publish("Creating Events...");
		while (tbl.findNextClass()){
                    cal.createRecurringEvent();
		}
                //Delete duplicates
		publish("Removing Old Events...");
		cal.removeOldEvents();
		publish("Sending Batch...");
		cal.insertBatch();
		long end = System.currentTimeMillis();
		publish("Done! " + "("+(end-start)+" ms)");

		//Change back to normal cursor
		Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
		setCursor(normalCursor);

                return null;
            }

            @Override
            protected void process(List<String> textL) {
                String text = textL.get(textL.size()-1);
                statusIndicator.setText(text);
            }
        }
	
	/*public void updateStatus(String text){
            System.out.print(text);
            statusIndicator.setText(text);
	}*/

	/**
	 * Opens a JFileChooser
	 */
	private void browseForTimetable(){
		int returnVal = fileChooser.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			/*if (!fileChooser.getSelectedFile().getName().equals("view_timetable.aspx.htm")){
                if (JOptionPane.showConfirmDialog(calendarPanel, "This may be the wrong file.\n\n Want me to try and find the right one?", "Uh oh...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
                    System.out.println(fileChooser.getCurrentDirectory().toString()+File.separator+"view_timetable.aspx.htm");

                }
            }*/
			pathField.setText(fileChooser.getSelectedFile().getPath());
		}
	}

	/**
	 * @param args the command line arguments
	 */
	/*public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				new ApplicationView().setVisible(true);
			}
		});
	}*/

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JMenuItem aboutMenuItem;
	private javax.swing.JButton browseButton;
	private javax.swing.JPanel calendarPanel;
	private javax.swing.JLabel calendarPanelHeaderLabel;
	private javax.swing.JButton createCalButton;
	private javax.swing.JMenuItem createCalMenuItem;
	private javax.swing.JFileChooser fileChooser;
	private javax.swing.JMenu fileMenu;
	private javax.swing.JMenu helpMenu;
	private javax.swing.JButton loginButton;
	private javax.swing.JLabel loginStatusLabel;
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JMenuItem openTimetableMenuItem;
	private javax.swing.JPasswordField passwordField;
	private javax.swing.JLabel passwordLabel;
	private javax.swing.JTextField pathField;
	private JLabel statusIndicator;
	private javax.swing.JPanel timetablePanel;
	private javax.swing.JLabel timetablePanelHeaderLabel;
	private javax.swing.JTextField usernameField;
	private javax.swing.JLabel usernameLabel;
	// End of variables declaration//GEN-END:variables

}
